package vn.com.demand.lux.view;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.ViewPart;

import vn.com.demand.lux.Activator;
import vn.com.demand.lux.criteria.UpdateIssuingExpenseCriteria;
import vn.com.demand.lux.dao.UpdateIssuingExpenseDao;
import vn.com.demand.lux.model.UpdateIssuingExpenseBean;
import vn.com.demand.lux.view.contentprovider.UpdateIssuingExpenseContentProvider;
import vn.com.demand.lux.view.labelprovider.UpdateIssuingExpenseLabelProvider;
import vn.com.demand.util.DpUtils;
import vn.com.demand.util.Validator;
import vn.com.demand.widget.SearchableDialogActivator;
import vn.com.demand.widget.SelectItemCodeHeader;
import vn.com.demand.widget.SelectMultiItemsTableActivator;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * 
 * @author Huynh Tan Tai <httcntt@yahoo.com>
 *
 */
public class UpdateIssuingExpense extends ViewPart {

	private org.eclipse.swt.widgets.List list;
	public static final String ID = "vn.com.demand.lux.view.UpdateIssuingExpense"; //$NON-NLS-1$
	private SearchableDialogActivator orginalLedgerCode;
	private SearchableDialogActivator changedLedgerCode;
	private Table table;
	private DateChooserCombo fromDate;
	private DateChooserCombo toDate;
	private TableViewer tableViewer;
	private static UpdateIssuingExpenseCriteria issuingExpenseCriteria;
	private List<UpdateIssuingExpenseBean> updateIssuingList;
	private Button runButton;

	/**
	 * Create contents of the view part
	 * 
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(Display.getCurrent());
		Composite container = toolkit.createComposite(parent, SWT.NONE);
		container.setLayout(new FillLayout());
		toolkit.paintBordersFor(container);

		final Form luxPaymnetForm = toolkit.createForm(container);
		luxPaymnetForm.setText("Update Issuing Expense");
		final Composite body = luxPaymnetForm.getBody();
		body.setLayout(new FormLayout());
		toolkit.paintBordersFor(body);

		final Section generalInformationSection = toolkit.createSection(body,
				Section.COMPACT | Section.TITLE_BAR | Section.FOCUS_TITLE);
		final FormData fd_generalInformationSection = new FormData();
		fd_generalInformationSection.bottom = new FormAttachment(0, 110);
		fd_generalInformationSection.top = new FormAttachment(0, 0);
		fd_generalInformationSection.right = new FormAttachment(100, -5);
		fd_generalInformationSection.left = new FormAttachment(0, 0);
		generalInformationSection.setLayoutData(fd_generalInformationSection);
		generalInformationSection.setText("General Information");

		final Composite composite = new Composite(generalInformationSection,
				SWT.NONE);
		toolkit.adapt(composite);
		generalInformationSection.setClient(composite);

		final Label fromDateLabel = toolkit.createLabel(composite,
				"From date:", SWT.NONE);
		fromDateLabel.setBounds(5, 6, 67, 19);
		fromDateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel
				.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Label fromDateLabel_1 = toolkit.createLabel(composite,
				"Issuing purpose:", SWT.NONE);
		fromDateLabel_1.setBounds(273, 32, 80, 19);
		fromDateLabel_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label fromDateLabel_2 = toolkit.createLabel(composite,
				"To date:", SWT.NONE);
		fromDateLabel_2.setBounds(5, 32, 67, 19);
		fromDateLabel_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		// text = toolkit.createText(composite, null, SWT.NONE);
		SelectItemCodeHeader header = new SelectItemCodeHeader(null,
				"select * from DEMAND_IssuingPurpose");

		final Label fromDateLabel_1_1 = toolkit.createLabel(composite,
				"Original ledger code:", SWT.NONE);
		fromDateLabel_1_1.setBounds(5, 58, 106, 19);
		fromDateLabel_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label fromDateLabel_1_1_1 = toolkit.createLabel(composite,
				"Changed ledger code:", SWT.NONE);
		fromDateLabel_1_1_1.setBounds(273, 6, 106, 19);
		fromDateLabel_1_1_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		fromDateLabel_1_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		fromDate = new DateChooserCombo(composite, SWT.BORDER);
		fromDate.setBounds(117, 6, 112, 20);
		fromDate.setCapture(true);
		fromDate.setLayout(null);
		DateFormatter dateFormatter = new DateFormatter(Activator.getDefault()
				.getDateFormatTypePreferences());
		fromDate.setFormatter(dateFormatter);
		toolkit.adapt(fromDate);

		toDate = new DateChooserCombo(composite, SWT.BORDER);
		toDate.setBounds(117, 32, 112, 20);
		DateFormatter dateFormatter2 = new DateFormatter(Activator.getDefault()
				.getDateFormatTypePreferences());
		toDate.setFormatter(dateFormatter2);
		toolkit.adapt(toDate);

		SelectItemCodeHeader header2 = new SelectItemCodeHeader(null,
				"select * from DEMAND_LedgerList");
		changedLedgerCode = new SearchableDialogActivator(composite, SWT.NONE,
				header2);
		changedLedgerCode.setBounds(383, 6, 153, 20);
		toolkit.adapt(changedLedgerCode);

		SelectItemCodeHeader header1 = new SelectItemCodeHeader(null,
				"select * from DEMAND_LedgerList");
		orginalLedgerCode = new SearchableDialogActivator(composite, SWT.NONE,
				header1);
		orginalLedgerCode.setBounds(117, 58, 112, 20);
		toolkit.adapt(orginalLedgerCode);

		list = new org.eclipse.swt.widgets.List(composite, SWT.V_SCROLL | SWT.MULTI | SWT.BORDER | SWT.H_SCROLL);
		toolkit.adapt(list, true, true);
		list.setBounds(383, 32, 153, 45);

		final Button button = toolkit.createButton(composite, "+", SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doAddIssueingPurpose();
			}
		});
		button.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/db_add.png"));
		button.setForeground(SWTResourceManager.getColor(0, 0, 255));
		button.setFont(SWTResourceManager.getFont("Tahoma", 10, SWT.BOLD));
		button.setBounds(550, 32, 28, 19);

		final Button button_1 = toolkit.createButton(composite, "-", SWT.NONE);
		button_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doRemoveSelectedIssuingPurpose();
			}
		});
		button_1.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/14_layer_deletelayer.png"));
		button_1.setBounds(550, 58, 28, 19);

		Composite composite_2;

		final Section detailInformationSection = toolkit.createSection(body,
				Section.TITLE_BAR);
		final FormData fd_detailInformationSection = new FormData();
		fd_detailInformationSection.bottom = new FormAttachment(100, -30);
		fd_detailInformationSection.right = new FormAttachment(100, -5);
		fd_detailInformationSection.top = new FormAttachment(0, 115);
		fd_detailInformationSection.left = new FormAttachment(0, 5);
		detailInformationSection.setLayoutData(fd_detailInformationSection);
		detailInformationSection.setText("Detail Information");

		final Composite composite_1 = toolkit.createComposite(
				detailInformationSection, SWT.NONE);
		composite_1.setLayout(new FillLayout());
		toolkit.paintBordersFor(composite_1);
		detailInformationSection.setClient(composite_1);

		tableViewer = new TableViewer(composite_1, SWT.FULL_SELECTION | SWT.BORDER);
		tableViewer.setContentProvider(new UpdateIssuingExpenseContentProvider());
		tableViewer.setLabelProvider(new UpdateIssuingExpenseLabelProvider());
		table = tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		toolkit.adapt(table, true, true);

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.setWidth(94);
		newColumnTableColumn.setText("Contact Number");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(78);
		newColumnTableColumn_1.setText("Ledger Code");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(104);
		newColumnTableColumn_2.setText("Ledger Name");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_3.setWidth(80);
		newColumnTableColumn_3.setText("Journal Code");

		final TableColumn newColumnTableColumn_4 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_4.setWidth(84);
		newColumnTableColumn_4.setText("Entry Number");

		final TableColumn newColumnTableColumn_5 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_5.setWidth(100);
		newColumnTableColumn_5.setText("Our Reference");

		final TableColumn newColumnTableColumn_6 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_6.setWidth(70);
		newColumnTableColumn_6.setText("Amount");

		final TableColumn newColumnTableColumn_7 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_7.setWidth(200);
		newColumnTableColumn_7.setText("Query 1");

		final TableColumn newColumnTableColumn_8 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_8.setWidth(200);
		newColumnTableColumn_8.setText("Query 2");
		composite_2 = new Composite(body, SWT.NONE);
		composite_2.setLayout(new FillLayout());
		final FormData fd_composite_2 = new FormData();
		fd_composite_2.left = new FormAttachment(100, -205);
		fd_composite_2.top = new FormAttachment(100, -30);
		fd_composite_2.bottom = new FormAttachment(100, -7);
		fd_composite_2.right = new FormAttachment(100, 0);
		composite_2.setLayoutData(fd_composite_2);
		toolkit.adapt(composite_2);

		final Button refreshButton = new Button(composite_2, SWT.NONE);
		refreshButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/reload.png"));
		refreshButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				try {
					doRefesh();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		toolkit.adapt(refreshButton, true, true);
		refreshButton.setText("&Refresh");

		runButton = new Button(composite_2, SWT.NONE);
		runButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/run.png"));
		runButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doRun();
			}
		});
		toolkit.adapt(runButton, true, true);
		runButton.setText("R&un");
		runButton.setEnabled(false);

		final Button closeButton = new Button(composite_2, SWT.NONE);
		closeButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/shutdown.png"));
		closeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doClose();
			}
		});
		toolkit.adapt(closeButton, true, true);
		closeButton.setText("Clos&e");

		createActions();
		initializeToolBar();
		initializeMenu();
	}

	protected void doRemoveSelectedIssuingPurpose() {
		String[] str = list.getSelection();
		if (null != str && str.length > 0) {
			for (int i = 0; i < str.length; i++) {
				list.remove(str[i]);
			}
		}
	}

	protected void doAddIssueingPurpose() {
		String sql = "SELECT selcode as code, oms30_0 as description FROM  dbo.ordsel";
		SelectMultiItemsTableActivator dlg = new SelectMultiItemsTableActivator(this.getViewSite().getShell(), sql);
		if (dlg.open() == org.eclipse.jface.dialogs.Dialog.OK) {
			String[] str = dlg.getSelectedItemCode();
			if (str != null && str.length > 0) {
				list.removeAll();
				for (int i = 0; i < str.length; i++) {
					list.add(str[i]);
				}
			}
			if (list.getItemCount() > 0) {
				Color white = new Color(null, 255, 255, 255);
				list.setBackground(white);
			}
		}
	}

	private void doRefesh() {
		if (doValidate()) {
			try {
				String fDate = fromDate.getText();
				String tDate = toDate.getText();
				String dateFormat = Activator.getDefault().getDateFormatTypePreferences();
				Date fromDate = DpUtils.parseDate(fDate, dateFormat);
				Date toDate = DpUtils.parseDate(tDate, dateFormat);
//				String issuing = issuingPurpose.getText().trim();
				String original = orginalLedgerCode.getText().trim();
				String changed = changedLedgerCode.getText().trim();
				issuingExpenseCriteria = new UpdateIssuingExpenseCriteria();
				issuingExpenseCriteria.setFromDate(fromDate);
				issuingExpenseCriteria.setToDate(toDate);
				issuingExpenseCriteria.setIssuingPurposes(list.getItems());
				issuingExpenseCriteria.setOriginalLedgerCode(original);
				issuingExpenseCriteria.setChangedLedgerCode(changed);
				updateIssuingList = UpdateIssuingExpenseDao.searchUpdateIssuingExpenses(issuingExpenseCriteria);
				tableViewer.setInput(updateIssuingList);
				if (updateIssuingList.isEmpty()) {
					MessageDialog.openInformation(null, "Information", "There is no issue match with those criteria");
				}
				runButton.setEnabled(!updateIssuingList.isEmpty());
			} catch (RuntimeException e) {
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}
	}

	private void doRun() {
		if (issuingExpenseCriteria == null) {
			MessageDialog.openError(null, "Error", "Can not run query with no data");
		} else {
			if (updateIssuingList != null && !updateIssuingList.isEmpty()) {
				try {
					UpdateIssuingExpenseDao.updateIssuingExpense(issuingExpenseCriteria, updateIssuingList);
					MessageDialog.openInformation(null, "Message", "Data was updated");
				} catch (SQLException e) {
					e.printStackTrace();
					MessageDialog.openError(null, "Error", "Data can not update");
				}
			} else {
				MessageDialog.openError(null, "Error", "Can not run query with no data");
			}
		}
	}

	private void doClose() {
		this.getViewSite().getWorkbenchWindow().getActivePage().hideView(this);
	}

	public boolean doValidate() {
		Color warningColor = new Color(null, 252, 216, 225);
		Color white = new Color(null, 255, 255, 255);
		if (null == fromDate.getValue()) {
			MessageDialog.openError(null, "Error", "From date can not be empty ");
			fromDate.setBackground(warningColor);
			fromDate.setFocus();
			return false;
		} else {
			fromDate.setBackground(white);
		}
		if (null == toDate.getValue()) {
			MessageDialog.openError(null, "Error", "To date can not be empty ");
			toDate.setBackground(warningColor);
			toDate.setFocus();
			return false;
		} else {
			toDate.setBackground(white);
		}
		if (fromDate.getValue().after(toDate.getValue())) {
			MessageDialog.openError(null, "Error", "From date can not be after To date");
			toDate.setBackground(warningColor);
			toDate.setFocus();
			return false;
		} else {
			toDate.setBackground(white);
		}
		if (list.getItemCount() == 0) {
			MessageDialog.openError(null, "Error", "Issuing purpose must be selected");
			list.setBackground(warningColor);
			list.setFocus();
			return false;
		} else {
			list.setBackground(white);
		}
//		if (!Validator.isValidIssuingPurpose(issuingPurpose.getText().trim())) {
//			MessageDialog.openError(null, "Error", "Issuing Purpose Code is not valid");
//			issuingPurpose.setBackground(warningColor);
//			issuingPurpose.setFocus();
//			return false;
//		} else {
//			issuingPurpose.setBackground(white);
//		}
		if (!Validator.isValidAccountNumber(changedLedgerCode.getText().trim())) {
			MessageDialog.openError(null, "Error", "Changed Ledger Code is not valid");
			changedLedgerCode.setBackground(warningColor);
			changedLedgerCode.setFocus();
			return false;
		} else {
			changedLedgerCode.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(orginalLedgerCode.getText().trim())) {
			MessageDialog.openError(null, "Error", "Original Ledger Code is not valid");
			orginalLedgerCode.setBackground(warningColor);
			orginalLedgerCode.setFocus();
			return false;
		} else {
			orginalLedgerCode.setBackground(white);
		}
		return true;
	}

	public static UpdateIssuingExpenseCriteria getIssuingExpenseCriteria() {
		return issuingExpenseCriteria;
	}
	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars()
				.getToolBarManager();
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
		IMenuManager menuManager = getViewSite().getActionBars()
				.getMenuManager();
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
